//
//  GetBackPassWordViewController.m
//  Consume100
//
//  Created by eliot on 16/3/21.
//  Copyright © 2016年 aleven. All rights reserved.
//

#import "GetBackPassWordViewController.h"
#import "UpdatePasswordSucceedViewController.h"
#define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
@interface GetBackPassWordViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;

@property (weak, nonatomic) IBOutlet UITextField *enterTextField;

@property (weak, nonatomic) IBOutlet UITextField *submitTextField;


@end

@implementation GetBackPassWordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.viewTitle;
    self.submitBtn.backgroundColor = [UIColor colorWithRed:236/255.0 green:62/255.0 blue:70/255.0 alpha:1];
    self.submitBtn.layer.cornerRadius = 4;
    self.submitBtn.layer.masksToBounds = YES;
    self.view.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
    [self.submitBtn setBackgroundImage:[GetBackPassWordViewController imageWithColor:[UIColor colorWithRed:255/255.0 green:88/255.0 blue:88/255.0 alpha:1] andframe:self.submitBtn.frame] forState:UIControlStateNormal];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.enterTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.submitTextField.keyboardType = UIKeyboardTypeASCIICapable;
    self.enterTextField.delegate = self;
    self.submitTextField.delegate = self;
    
    /** 设置导航啦样式*/
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.navigationController.navigationBar.translucent = NO;
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
    
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
    
    
    BOOL canChange = [string isEqualToString:filtered];
    
    
    return canChange;
}


+ (UIImage *)imageWithColor:(UIColor *)color andframe:(CGRect)frame {
    CGRect rect = frame;
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

+(GetBackPassWordViewController*)CreatGetBackPassWordViewController{
    
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    GetBackPassWordViewController *password=[story instantiateViewControllerWithIdentifier:@"GetBackPassWordViewController"];
    return password;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

//点击提交按钮
- (IBAction)clickSubmitBtn:(id)sender {
    [self.submitBtn setBackgroundImage:[GetBackPassWordViewController imageWithColor:[UIColor colorWithRed:241/255.0 green:77/255.0 blue:77/255.0 alpha:1] andframe:self.submitBtn.frame] forState:UIControlStateSelected];
    
    
    
    if ([self.viewTitle  isEqual: @"找回密码"]) {//找回密码
        
        
        
    }else if ([self.viewTitle  isEqual: @"设置支付密码"]){//设置支付密码
        
        UpdatePasswordSucceedViewController *vc = [UpdatePasswordSucceedViewController CreatUpdatePasswordSucceedViewController];
        [self creatNav:vc];
        
    }else {
    
        if (![self.enterTextField.text isEqualToString:self.submitTextField.text]) {
            
            [MBProgressHUD showError:@"密码不一致"];
        }else {
            
            if (!(self.enterTextField.text.length > 0)) {
                [MBProgressHUD showError:@"请输入密码"];
            }else {
                NSData *encodeData = [[NSUserDefaults standardUserDefaults] objectForKey:@"userModel"];
                UserModel *model = [NSKeyedUnarchiver unarchiveObjectWithData:encodeData];
                AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                manager.responseSerializer = [AFHTTPResponseSerializer serializer];
                manager.requestSerializer.timeoutInterval = 5;
                NSDictionary *dic = @{@"phone":model.phone, @"pwd":self.enterTextField.text, @"pwds":self.submitTextField.text,};
                NSString *baseUrl = [NSString stringWithFormat:@"%@changePwd.jhtml", MyBaseURL];
                [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    NSDictionary *dddic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                    
                    NSLog(@"%@", dddic);
                    
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [MBProgressHUD hideHUD];
                        [MBProgressHUD showError:@"链接超时,请检查网络"];
                    });
                }];
            }
            
        }
    
    }
    
    
}

//创建模态导航控制器
-(void)creatNav:(UIViewController *)view{
    
    UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:view];
    nav.navigationBar.barTintColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    view.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_back"] style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)dismiss {
    [self dismissViewControllerAnimated:YES completion:nil];
}

//点击空白处收回键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.enterTextField resignFirstResponder];
    [self.submitTextField resignFirstResponder];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
